package com.ajou.adonate.imap;


import java.io.IOException;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.*;

public class FileUploader extends Thread {
	
	private String m_FilePath = null;
	private Boolean m_IsSetFlag = false;
	private UserSession m_TempSession = null;
	private int m_Hash = 0;
	//private int m_MailId = 0;
	private String m_FileName = null;
	private int m_Index = 0;
	private int m_FlieSize = 0;
	private int m_DirectoryId=0;
	
	public FileUploader(UserSession Temp_s) {
		super();
		m_TempSession = Temp_s;
	}
	
	public void UploadNewFile(String fileName,String filePath, int FilehashCode,/*int index, */ int filesize/*, int directoryId*/) {
		m_Hash = FilehashCode;
		m_FileName = fileName;
		m_FilePath = filePath;
		m_FlieSize = filesize;
	}
	
	public void run() {
		Multipart MP = null;
		
		String from = "adonate.ajou@gmail.com";
		String to = "tapaha7@gmail.com";
		String subject = "[ADONATE]" +
				   "[File Name:"+m_FileName + "]" +
				   "[File Hash:" + Integer.toString(m_Hash) + "]" +
				   "[Size:" + Integer.toString(m_FlieSize) +"]";
		
		try {
		    // create a message
		    MimeMessage msg = new MimeMessage(m_TempSession.getSession());
		    msg.setHeader("content-type", "text/html;charset=UTF-8");
		    msg.setFrom(new InternetAddress(from));
		    InternetAddress[] address = {new InternetAddress(to)};
		    msg.setRecipients(Message.RecipientType.TO, address);
		    msg.setSubject(subject);

		    MimeBodyPart MBP_File = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(m_FilePath); 
			MBP_File.setDataHandler(new DataHandler(fds));
			
			MBP_File.setFileName(fds.getName());
			
			MP = new MimeMultipart();
			MP.addBodyPart(MBP_File);
			//MP.addBodyPart(MBP_Text);
			
			msg.setContent(MP);

		    // set the Date: header
		    msg.setSentDate(new Date());

		    Transport trans = m_TempSession.getSession().getTransport("smtp");
			trans.connect("smtp.gmail.com", m_TempSession.getID(), m_TempSession.getPassword());
			trans.sendMessage(msg, msg.getAllRecipients());
			trans.close();
		    
		} catch (MessagingException mex) {
		    mex.printStackTrace();
		    Exception ex = null;
		    if ((ex = mex.getNextException()) != null) {
		    	ex.printStackTrace();
		    }
		}
		
	}
}